package com.tianqu.tms.www.rental.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsAction;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.entity.Codes;
import com.tianqu.tms.entity.RentalContractInfo;
import com.tianqu.tms.www.rental.actionform.RentalContractAddInputForm;
import com.tianqu.tms.www.rental.controller.RentalContractSearchListController;
import com.tianqu.tms.www.rental.controller.RentalContractUpdateHistroySearchListController;
import com.tianqu.tms.www.rental.viewhelper.RentalContractAddInputViewHelper;

/**
 * 合同查询/修改-合同一览action
 * @author mufeiyu
 */
public class RentalContractUpdateHistroySearchListAction extends TmsAction {

	private Logger logger = Logger.getLogger(RentalContractUpdateHistroySearchListAction.class);
	
	public final static String PAGENO = "pageNo";
	public final static String SORTKEY = "sortKey";
	public final static String MAXINDEX = "maxIndex";
	public final static String ASC = "asc";
	
	@Override
	protected ActionForward doAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			UserContext uc) throws Exception {
		
		logger.debug(this.getClass().getName() + "#execute was called.");
		Codes codes = Codes.getInstance();
		RentalContractAddInputViewHelper viewhelper = new RentalContractAddInputViewHelper();
		RentalContractAddInputViewHelper viewhelper1 = new RentalContractAddInputViewHelper();

		if(uc.getAttribute(TmsConstants.VIEWHELP)!=null){
			uc.removeAttribute(TmsConstants.VIEWHELP);
		}
		if(request.getParameter(PAGENO) == null ) {
			if(uc.getAttribute(PAGENO) == null) {
				uc.setAttribute(PAGENO, viewhelper.getPageNo());
				uc.setAttribute(SORTKEY, "8");
				uc.setAttribute(MAXINDEX, "20");
				uc.setAttribute(ASC, "false");
				RentalContractAddInputForm rentalForm = (RentalContractAddInputForm) uc.getInputForm();
				String[] handleType = rentalForm.getHandleType();
				viewhelper.setSerial(rentalForm.getSerial());
				viewhelper.setHandleName(rentalForm.getHandleName());
				viewhelper.setHandleTypeList(convertHandleType(rentalForm.getHandleType()));
				viewhelper.setHandleDateS(rentalForm.getHandleDateS());
				viewhelper.setHandleDateE(rentalForm.getHandleDateE());
				uc.setAttribute(TmsConstants.VIEWHELP, viewhelper);
				
				if ("2".equals(uc.getAttribute("searchFlg"))) {
					
					uc.removeAttribute("searchFlg");
					
					// 操作状态
					List handleTypeList = codes.getCodeslistByItemId(Codes.CONTRACT_UPDATE_TYPE);
					
					if (StringUtil.isNullOrBlank(rentalForm.getSerial()) && StringUtil.isNullOrBlank(rentalForm.getHandleName()) 
							&& StringUtil.isNullOrBlank(rentalForm.getHandleDateS()) && StringUtil.isNullOrBlank(rentalForm.getHandleDateE())
							&& (null == handleType || handleType.length == 0 || handleType.length == handleTypeList.size())) {
						setErrorsToRequest(request, TmsConstants.U0037, null); // 必须输入至少一个查询条件。
						uc.setAttribute("errFlg", "true");
	
					}
					//操作日期 / 区间check
					if ((!StringUtil.isNullOrBlank(rentalForm.getHandleDateS()))&&(!StringUtil.isNullOrBlank(rentalForm.getHandleDateE()))) {	
						SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
						//操作日期前段
						Date handleDateS = formatDate.parse(rentalForm.getHandleDateS());
						//操作日期后端				
						Date handleDateE = formatDate.parse(rentalForm.getHandleDateE());
						// 比较
						if (handleDateE.compareTo(handleDateS) < 0) {
							String[] param = {"操作日期/区间"};
							setErrorsToRequest(request, TmsConstants.U0038, param); //操作日期/区间填写的后一个日期不能比前一个日期小。
							uc.setAttribute("errFlg", "true");
						}
					}
					
					if ("true".equals(uc.getAttribute("errFlg"))) {
						return mapping.getInputForward();
					}
				}else {
					uc.setAttribute(PAGENO, uc.getAttribute(PAGENO));
					uc.setAttribute(SORTKEY, uc.getAttribute(SORTKEY));
					uc.setAttribute(MAXINDEX, uc.getAttribute(MAXINDEX));
					uc.setAttribute(ASC, uc.getAttribute(ASC));
				}
			}
		} else {
			uc.setAttribute(PAGENO, request.getParameter(PAGENO));
			uc.setAttribute(SORTKEY, request.getParameter(SORTKEY));
			uc.setAttribute(MAXINDEX, request.getParameter(MAXINDEX));
			uc.setAttribute(ASC, request.getParameter(ASC));
		}
				
		RentalContractUpdateHistroySearchListController controller = new RentalContractUpdateHistroySearchListController();
		controller.execute(uc);
		
		viewhelper1 = (RentalContractAddInputViewHelper)uc.getAttribute(TmsConstants.VIEWHELP);
		
		if (viewhelper1.getRentalInfoUpdateHistroyList().size() == 0) {//结果为空
			uc.setAttribute(TmsConstants.VIEWHELP, viewhelper);
			setErrorsToRequest(request, TmsConstants.U0039, null);
			uc.setAttribute("errFlg", "true");
			return mapping.getInputForward();
		}		

		RentalContractInfo rentalContractInfo = (RentalContractInfo)uc.getAttribute(RentalContractSearchListController.PAGING);
		
		// viewhelp中设置翻页。
		viewhelper1.setPageNo(Integer.toString(rentalContractInfo.getPageNo()));
		viewhelper1.setMaxIndex(Integer.toString(rentalContractInfo.getMaxIndex()));
		viewhelper1.setAsc(Boolean.toString(rentalContractInfo.isAsc()));
		viewhelper1.setSortKey(Integer.toString(rentalContractInfo.getSortKey()));
		viewhelper1.setTotalCount(Integer.toString(rentalContractInfo.getTotalCount()));
		viewhelper1.setDateFrom(Integer.toString(rentalContractInfo.getDateFrom()));
		viewhelper1.setDateTo(Integer.toString(rentalContractInfo.getDateTo()));
		//去掉缓存
		if(uc.getAttribute("confirmForm")!=null)
		{
			uc.removeAttribute("confirmForm");
		}
		request.setAttribute(TmsConstants.VIEWHELP,viewhelper1);
		uc.removeAttribute(TmsConstants.VIEWHELP);
		logger.debug(this.getClass().getName() + "#execute was completed.");
		return mapping.findForward(TmsConstants.SUCCESS);
	}
	
	private List convertHandleType(String[] handleType) throws TmsDaoException{
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
		if(null != handleType && handleType.length > 0){
			for (int i = 0; i < handleType.length; i++){
				int itemCode = StringUtils.isNumeric(handleType[i])?Integer.parseInt(handleType[i]):-1;
				map.put(itemCode, itemCode);
			}
		}
		List codeslist = Codes.getInstance().getCodeslistByItemId(Codes.CONTRACT_UPDATE_TYPE);
		for (Object object : codeslist) {
			String checked = "";
			HashMap codesMap = (HashMap)object;
			if(map.get(codesMap.get("itemCode"))!=null ) checked = "checked";
			codesMap.put("checked", checked);
		}
		return codeslist;
	}

}
